package org.example.wx.user.web;

import lombok.Data;
import org.example.wx.user.entity.WxUser;
import org.example.wx.user.service.WxUserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/wx")
public class WxAuthController {

    private final WxUserService wxUserService;

    public WxAuthController(WxUserService wxUserService) {
        this.wxUserService = wxUserService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        try {
            // 支持用户名密码登录
            if (request.getUsername() != null && request.getPassword() != null) {
                Optional<WxUser> userOpt = wxUserService.loginUser(request.getUsername(), request.getPassword());
                if (userOpt.isPresent()) {
                    WxUser user = userOpt.get();
                    Map<String, Object> body = new HashMap<>();
                    body.put("token", "user-" + user.getId());
                    Map<String, Object> info = new HashMap<>();
                    info.put("avatarUrl", user.getAvatarUrl());
                    info.put("nickName", user.getNickName());
                    body.put("userInfo", info);
                    return ResponseEntity.ok(body);
                } else {
                    Map<String, Object> error = new HashMap<>();
                    error.put("message", "用户名或密码错误");
                    return ResponseEntity.badRequest().body(error);
                }
            }
            
            // 原微信登录逻辑保留
            String openId = request.getOpenId();
            if (openId == null || openId.isEmpty()) {
                openId = request.getCode();
            }
            WxUser user = wxUserService.registerIfAbsent(openId, request.getNickName(), request.getAvatarUrl());
            Map<String, Object> body = new HashMap<>();
            body.put("token", "wx-" + openId);
            Map<String, Object> info = new HashMap<>();
            info.put("avatarUrl", user.getAvatarUrl());
            info.put("nickName", user.getNickName());
            body.put("userInfo", info);
            return ResponseEntity.ok(body);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
        try {
            WxUser user = wxUserService.registerUser(request.getUsername(), request.getPassword(), request.getNickname());
            Map<String, Object> body = new HashMap<>();
            body.put("message", "注册成功");
            body.put("userId", user.getId());
            return ResponseEntity.ok(body);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @GetMapping("/profile")
    public ResponseEntity<?> getProfile(@RequestHeader("Authorization") String token) {
        try {
            // 从token中提取用户ID
            Long userId = extractUserIdFromToken(token);
            Optional<WxUser> userOpt = wxUserService.findById(userId);
            
            if (userOpt.isPresent()) {
                WxUser user = userOpt.get();
                Map<String, Object> profile = new HashMap<>();
                profile.put("id", user.getId());
                profile.put("nickName", user.getNickName());
                profile.put("avatarUrl", user.getAvatarUrl());
                profile.put("gender", user.getGender());
                profile.put("phoneNumber", user.getPhoneNumber());
                profile.put("country", user.getCountry());
                profile.put("province", user.getProvince());
                profile.put("city", user.getCity());
                profile.put("username", user.getUsername());
                return ResponseEntity.ok(profile);
            } else {
                Map<String, Object> error = new HashMap<>();
                error.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(error);
            }
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(@RequestHeader("Authorization") String token, @RequestBody UpdateProfileRequest request) {
        try {
            Long userId = extractUserIdFromToken(token);
            WxUser updatedUser = wxUserService.updateProfile(userId, request);
            
            Map<String, Object> profile = new HashMap<>();
            profile.put("nickName", updatedUser.getNickName());
            profile.put("avatarUrl", updatedUser.getAvatarUrl());
            profile.put("gender", updatedUser.getGender());
            profile.put("phoneNumber", updatedUser.getPhoneNumber());
            profile.put("country", updatedUser.getCountry());
            profile.put("province", updatedUser.getProvince());
            profile.put("city", updatedUser.getCity());
            
            Map<String, Object> body = new HashMap<>();
            body.put("message", "更新成功");
            body.put("userInfo", profile);
            return ResponseEntity.ok(body);
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    private Long extractUserIdFromToken(String token) {
        // 简单的token解析，实际项目中应该使用JWT等安全方案
        if (token.startsWith("user-")) {
            return Long.parseLong(token.substring(5));
        } else if (token.startsWith("wx-")) {
            // 对于微信登录的用户，需要通过openId查找
            String openId = token.substring(3);
            Optional<WxUser> user = wxUserService.findByOpenId(openId);
            if (user.isPresent()) {
                return user.get().getId();
            }
        }
        throw new RuntimeException("无效的token");
    }

    @Data
    public static class LoginRequest {
        private String code;
        private String openId;
        private String nickName;
        private String avatarUrl;
        private String username;
        private String password;
    }

    @Data
    public static class RegisterRequest {
        private String username;
        private String password;
        private String nickname;
    }

    @Data
    public static class UpdateProfileRequest {
        private String nickName;
        private String avatarUrl;
        private Integer gender;
        private String phoneNumber;
        private String country;
        private String province;
        private String city;
    }
}



